package com.arcbbs.service.impl;

import com.arcbbs.config.WebConfig;
import com.arcbbs.constant.BaseConstant;
import com.arcbbs.entity.*;
import com.arcbbs.enums.FileUploadTypeEnum;
import com.arcbbs.exception.BaseException;
import com.arcbbs.mapper.FormArticleMapper;
import com.arcbbs.mapper.ForumArticleAttachmentMapper;
import com.arcbbs.result.PageResult;
import com.arcbbs.service.FormArticleService;

import com.arcbbs.utils.FileUtils;
import com.arcbbs.utils.StringTools;
import com.arcbbs.utils.SysCacheUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class FormArticleServiceImpl implements FormArticleService {
    @Resource
    private FormArticleMapper formArticleMapper;
    @Resource
    private FileUtils fileUtils;
    @Resource
    private WebConfig webConfig;
    @Resource
    private ForumArticleAttachmentMapper forumArticleAttachmentMapper;

    @Override
    public PageResult selectbypage(ForumArticleQuery forumArticleQuery, Integer orderType) {

        PageHelper.startPage(forumArticleQuery.getPageNo(), 10);


        System.out.println(orderType);

        if (orderType == 1) {
            forumArticleQuery.setOrder("top_type desc,comment_count desc,good_count desc,read_count desc");
        } else if (orderType == 2) {
            forumArticleQuery.setOrder("post_time asc");
        } else if (orderType == 3) {
            forumArticleQuery.setOrder("post_time desc");
        }

        System.out.println(forumArticleQuery.getCurrentUserId() + "cir1");
        Page<ForumArticle> page = formArticleMapper.page1(forumArticleQuery);
        long total = page.getTotal();


        List<ForumArticle> list = page.getResult();

        return new PageResult(total, list);


    }

    @Override
    public void readArticle(HttpSession httpSession, String articleId) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        ForumArticle forumArticle = formArticleMapper.getbyid(articleId);
        //如果为空 或待审核或未登录或已删除。不能查看详情
//        if (forumArticle == null ||( forumArticle.getStatus().equals(0) &&(sessionWebUserDto ==null||
//                !sessionWebUserDto.getUserId().equals(forumArticle.getUserId()))||!sessionWebUserDto.getIsAdmin()
//        ||forumArticle.getStatus().equals(-1) )) {
//            throw new BaseException("该文章不存在");
//        }
        if (forumArticle == null || forumArticle.getStatus().equals(-1) || forumArticle.getStatus().equals(0)) {
            throw new BaseException("该文章不存在");
        }

        if (forumArticle.getStatus() == 1) {
            formArticleMapper.updateArticleNumber(0, 1, articleId);

        }
    }

    @Override
    public ForumArticle getbyid(String articleId) {
        ForumArticle forumArticle = formArticleMapper.getbyid(articleId);
        return forumArticle;
    }

    @Override
    public void updatearticle(SessionWebUserDto sessionWebUserDto, ForumArticle forumArticle, ForumArticleAttachment forumArticleAttachment, MultipartFile cover, MultipartFile attachment) {
        ForumArticle forumArticle1 = formArticleMapper.getbyid(forumArticle.getArticleId());
        if (!sessionWebUserDto.getIsAdmin() && !forumArticle.getUserId().equals(sessionWebUserDto.getUserId())) {
            throw new BaseException("无权限修改");
        }
        if (cover != null) {
            FileUploadDto fileUploadDto = fileUtils.uploadDto(cover, BaseConstant.FILE_FOLDER_IMAGE, FileUploadTypeEnum.ARTICLE_ATTACHMENT);
            forumArticle.setCover(fileUploadDto.getLocalpath());
        }
        if (forumArticleAttachment != null) {
            uploadAttachment(forumArticle, forumArticleAttachment, attachment, true);
            forumArticle.setAttachmentType(1);
        } else {
            forumArticle.setAttachmentType(0);
        }
        ForumArticleAttachment dbattachment = null;
        List<ForumArticleAttachment> list = forumArticleAttachmentMapper.selectbyid(forumArticle.getArticleId());
        if (!list.isEmpty()) {
            dbattachment = list.get(0);
        }
        if (dbattachment != null) {
            if (forumArticle.getAttachmentType() == 0) {
                new File(webConfig.getProjectFolder() + BaseConstant.FILE_FOLDER_FILE + BaseConstant.FILE_FOLDER_ATTACHMENT + dbattachment.getFilePath()).delete();
                forumArticleAttachmentMapper.deletebyfileid(dbattachment.getFileId());
            } else {
                if (!dbattachment.getIntegral().equals(forumArticleAttachment.getArticleId())) {
                    ForumArticleAttachment integralUpdatee = new ForumArticleAttachment();
                    integralUpdatee.setIntegral(forumArticleAttachment.getIntegral());
                    forumArticleAttachmentMapper.updatebyfileId(integralUpdatee, dbattachment.getFileId());
                }
            }
        }
        if(!sessionWebUserDto.getIsAdmin()){
            forumArticle.setStatus(0);
        }
        formArticleMapper.updateByarticleId1(forumArticle,forumArticle.getArticleId());

    }

    public void uploadAttachment(ForumArticle forumArticle, ForumArticleAttachment forumArticleAttachment, MultipartFile attachment, boolean istrue) {
        Integer allowSizemb = SysCacheUtils.getSysSetting().getSystemSettingPostDto().getAttachmentSize();
        long allowSize = allowSizemb * 1024 * 1024;
        if (attachment.getSize() > allowSize) {
            throw new BaseException("上传的附件过大");
        }
        ForumArticleAttachment forumArticleAttachment1 = null;
        if (istrue) {
            List<ForumArticleAttachment> list = forumArticleAttachmentMapper.selectbyid(forumArticle.getArticleId());
            if (!list.isEmpty()) {
                forumArticleAttachment1 = list.get(0);
                new File(webConfig.getProjectFolder() + BaseConstant.FILE_FOLDER_FILE + BaseConstant.FILE_FOLDER_ATTACHMENT + forumArticleAttachment1.getFilePath()).delete();


            }
        }
        FileUploadDto fileUploadDto = fileUtils.uploadDto(attachment, BaseConstant.FILE_FOLDER_ATTACHMENT, FileUploadTypeEnum.ARTICLE_ATTACHMENT);
        if (forumArticleAttachment1 == null) {
            forumArticleAttachment.setFileId(StringTools.getFinalString(15));
            forumArticleAttachment.setArticleId(forumArticle.getArticleId());
            forumArticleAttachment.setFileName(fileUploadDto.getOriginalFileName());
            forumArticleAttachment.setFilePath(fileUploadDto.getLocalpath());
            forumArticleAttachment.setFileSize((int) attachment.getSize());
            forumArticleAttachment.setDownloadCount(0);
            forumArticleAttachment.setFileType(4);
            forumArticleAttachment.setUserId(forumArticle.getUserId());
            forumArticleAttachmentMapper.insert(forumArticleAttachment);

        } else {
            ForumArticleAttachment uploadinfo = new ForumArticleAttachment();
            uploadinfo.setFileName(fileUploadDto.getOriginalFileName());
            uploadinfo.setFileSize((int) attachment.getSize());
            uploadinfo.setFilePath(fileUploadDto.getLocalpath());
            forumArticleAttachmentMapper.updateByarticleId(uploadinfo, forumArticleAttachment1.getFileId());


        }
    }
}

